const express = require('express')
const Router = express.Router()
const sql  =require('./sql/sql')
const {success,fail} = require('./utils/send')
const captcha = require("svg-captcha");
const decode = require('./token/token')
const tools = require('./utils/syntax')
const timing = require('./utils/timing')



Router.post('/orderSubmit',async (req,res)=>{
    let {name,price,mobile,quantity,address,detailAddress,goods} = req.body
    address = detailAddress + address
    let {token} = req.headers
    let result = await decode.getAccount(token,sql)
    let accountId = result[0].id
    //写入用户订单数据
    let time = timing()
    let syntax = "insert into customize_pay(name,mobile,address,price,quantity,accountId,addTime)  values (?,?,?,?,?,?,?)"
    let params = [name,mobile,address,price,quantity,accountId,time]
    let data = await sql(syntax,params)
    // 储存insertId 写入 orderDetail数据
    var orderNum = data.insertId
   

    let promiseList = []

    goods.forEach(item => {
        let {price,skuid,skunum} = item
        let params = [price,skuid,skunum,orderNum,accountId]
        let syntax = "insert into customize_orderdetail(price,skuId,skuNum,orderNum,accountId) values (?,?,?,?,?)"
        let result = sql(syntax,params)
        promiseList.push(result)
    })

    try{
        let cc = await Promise.all(promiseList)
        let syntax = "select * from customize_pay where orderId=?"
        let final = await sql(syntax,orderNum)
        success(res,final[0],'提交订单成功')
    }catch{
        fail(res,[],'提交订单失败')
    }
    
    // var totalmenus = goods.length-1 
    // for(let i = 0;i < goods.length; i++){
    //     let {price,skuid,skunum} = goods[i]
    //     let params = [price,skuid,skunum,orderNum,accountId]
    //     let syntax = "insert into customize_orderdetail(price,skuId,skuNum,orderNum,accountId) values (?,?,?,?,?)"
    //     sql(syntax,params).then(data =>{
    //         if(data.affectedRows >= 1){
    //             totalmenus--
    //         }
    //      })
         
    //      if(i == goods.length-1){
    //         if(totalmenus == 0){
    //             success(res,[],'提交订单成功')
    //         }else{

    //             fail(res,[],'提交订单失败')
    //         }
    //      }
    // }

    /* OkPacket {
        fieldCount: 0,
        affectedRows: 1,
        insertId: 5,
        serverStatus: 2,
        warningCount: 2,
        message: '',
        protocol41: true,
        changedRows: 0
       }
     */
})

Router.get('/orderStatus/:no',async (req,res)=>{
    let orderId = req.params.no
    let syntax = "select * from customize_pay where orderId=?"
    let result =await sql(syntax,orderId)
    
    if(result.length === 0){
        fail(res,[],'该订单不存在')
    }else{
        if(result[0].status == 0){
            res.send({
                status:201,
                data:result[0],
                payLink:`http://00mi.f3322.net:3000/api/paySuccess/${orderId}`,
                msg:'未支付成功'
            })

        }else{
            // success(res,result[0],'支付成功',)
            res.send({
                status:200,
                data:result[0],
                payLink:`http://00mi.f3322.net:3000/api/paySuccess/${orderId}`,
                msg:'支付成功'
            })
        }
    }
})

// 支付地址测试
Router.get('/paySuccess/:orderId',async (req,res)=>{
    let {orderId} = req.params
    // let syntax = "update nideshop_shopcart SET ischecked=? where uuid=? and skuid=?"
    let time = timing()
    let syntax = "update customize_pay set status='1', payTime=?  where orderId=?"
    let result =await sql(syntax,[time,orderId])
    if(result.affectedRows > 0){
        success(res,result.data,'支付成功')
    }else{
        fail(res,[],orderId+'支付失败') 
    }
})

// 获取个人订单
Router.post('/myOrder',async (req,res)=>{
    let {token} = req.headers
    let {limit,page} = req.body

    if(!token){
       fail(res,[],'请登陆')
        
    }else{
        try{
            let result = await decode.getAccount(token,sql)
            let accountId = result[0].id
            // console.log(accountId);  // 14 
            // let limitSyntax = tools('findPay') + ` limit ${limit} offset ${(page-1)*limit} order by orderId desc`
            // SELECT COUNT(*) FROM nideshop_goods where category_id=1008009
            let limitSyntax = tools('findPay') + `order by orderId desc limit ${limit} offset ${(page-1)*limit} `
            let totalList = 'SELECT COUNT(*) FROM customize_pay where accountId=?'
            let list = await sql(totalList,accountId)
            let order= await sql(limitSyntax,accountId) 
            if(order.length == 0){
                return res.send({status:200,data:[],msg:'你未有订单'})
            }

       /*   RowDataPacket {
                orderId: 138,
                name: 'liz',
                mobile: '13888888888',
                address: '中国广东省深圳市福田区龙洞2号',
                payments: '0',
                status: 1,
                price: 199,
                quantity: 1,
                accountId: 14
              },  */
            
            // 在这个数据中插入 goods 与 当前  goods 数量与总价
            let pList = []
            order.forEach( item =>{
                // 获取支付订单,从订单中查找包含的产品,再获取产品详情,
                let detailOrderSyntax ="select * from customize_orderdetail where accountId=? and orderNum=?" 
                
                pList.push(sql(detailOrderSyntax,[accountId,item.orderId]))
            })

           let pResult= await Promise.all(pList)


            // order.forEach((item,index)=>{
            //     item.goodsList = pResult[index]
            //     item.goodsList.forEach(citem =>{
            //         let goods = await sql(tools('goods'),citem.skuId)
            //         citem.goods = goods
            //     })
            // })
            let promiseC = []
            for(let i = 0;i < order.length; i++){
                order[i].goodsList = pResult[i]
                // promiseC[i]=i
                for(let j = 0; j < order[i].goodsList.length ; j++){
                    let goods = sql(tools('goods'),order[i].goodsList[j].skuId)
                    // order[i].goodsList[j].goods = goods
                    // promiseC[i][j]=goods
                    promiseC.push(goods)
                }
            }
            let dd = await Promise.all(promiseC)
            for(let i = 0;i < order.length; i++){
                for(var j = 0; j < order[i].goodsList.length ; j++){
                    order[i].goodsList[j].goods = dd.find(item =>{
                        return item[0].id == order[i].goodsList[j].skuId
                    })
                }
            }
            // success(res,order,'获取成功')
            res.send({
                status:200,
                order,
                total:list[0]['COUNT(*)'],
                msg:'请求成功'
            })
        }catch{
            fail(res,[],'非法用户')
        }
    }
    
    
    
})



module.exports = Router